<template>
  <div>
    <top-nav-bar :applyPageRoute="nowRouteTitle" @back="back"></top-nav-bar>
    <a-card :bordered="false" class="nowPage">
      <a-form-model
        :model="form"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        labelAlign="left"
        :rules="rules"
        ref="ruleForm"
      >
        <a-row>
          <a-col :md="8" :sm="24">
            <a-form-model-item label="考试名称" prop="name">
              <a-input v-model="form.name" placeholder="请输入(20字以内)"/>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-model-item label="考试科目" prop="subject_id">
              <a-select v-model="form.subject_id" placeholder="请选择" prop="subject_id">
                <a-select-option
                  :value="item.id"
                  v-for="item in Issubjects"
                  :key="item.id"
                   v-if="item.is_enable==1"
                >{{item.name}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-model-item label="满分" prop="full_marks">
              <a-input-number
                id="inputNumber"
                :min="1"
                v-model="form.full_marks"
                style="width:100%"
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="8" :sm="24">
            <a-form-model-item label="考试时间" prop="time">
              <a-date-picker @change="onChange" style="width: 100%;" v-model="form.time" />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-model-item label="成绩来源" prop="source_type">
              <a-radio-group v-model="form.source_type">
                <a-radio value="1">机构内</a-radio>
                <a-radio value="2">机构外</a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <a-row style="border-top: 1px solid #e8e8e8;padding-top:12px;">
        <!-- <a-col :span="24">
          <div class="a_row_bottom"></div>
        </a-col>-->
        <a-col :md="8" :sm="24">
          <span style="margin-right:8px">是否展示给家长:</span>
          <a-radio-group v-model="form.is_show">
            <a-radio value="1">展示</a-radio>
            <a-radio value="2">不展示</a-radio>
          </a-radio-group>
        </a-col>
        <a-col :md="8" :sm="24">
          <span style="margin-right:8px">排名、最高分、平均分是否展示给家长:</span>
          <a-radio-group v-model="form.is_statistics_show">
            <a-radio value="1">展示</a-radio>
            <a-radio value="2">不展示</a-radio>
          </a-radio-group>
        </a-col>
      </a-row>
    </a-card>
    <!-- 表格 -->
    <a-card :bordered="false" style="margin-top:25px;margin-bottom:80px;">
      <div style="display:flex; align-items: center;margin-bottom:15px;">
        <a-button @click="open1" style="margin-right:8px">添加学生</a-button>
        <a-button @click="open2" style="margin-right:12px">添加班级</a-button>
        <div style="width:100%;">
          <a-alert
            type="warning"
            message="保存草稿或发布时会自动计算最高分、平均分、学员排名"
            showIcon
            style="border:none;"
          ></a-alert>
        </div>
      </div>

      <a-table
        :columns="columns"
        :dataSource="form.score_arr"
        :pagination="false"
        :rowKey="record => record.student_id"
        class="user_management_table"
        style="border:1px solid #e8e8e8;"
      >
        <span slot="status" slot-scope="text,record">
          <a-radio-group @change="handleSizeChange(record)" v-model="record.status" style="margin-right:10px;">
            <a-radio-button value="1">参加考试</a-radio-button>
            <a-radio-button value="2">缺考</a-radio-button>
          </a-radio-group>
          <span v-if="record.status==1">
            <a-input-number
              id="inputNumber"
              :min="0"
              :max="form.full_marks"
              v-model="record.score"
            />分
          </span>
        </span>
        <span slot="comment" slot-scope="text,record">
          <a-textarea
            placeholder="请输入(150字以内)"
            :autoSize="{ minRows: 2, maxRows: 6 }"
            v-model="record.comment"
            :maxLength="150"
          />
        </span>
        <span slot="action" slot-scope="text,record">
          <a href="javascript:;" style="margin-left:10px;" @click="table_del(record)">删除</a>
        </span>
      </a-table>
    </a-card>

    <a-modal
      title="选择学生"
      v-model="visible1"
      @ok="handleOk1"
      :destroyOnClose="true"
      okText="选好了"
      width="800px"
    >
      <a-form>
        <a-row>
          <a-col :span="6">
            <a-form-item>
              <a-input  v-model="studentName"
                placeholder="请输入学员名称(回车搜索)"
                @pressEnter="$refs.table1.refresh(true)" >
                   <a-tooltip slot="suffix" title="请输入学员名称">
                  <a-icon
                    type="search"
                    style="color: rgba(0,0,0,.45)"
                    @click="$refs.table1.refresh(true)"
                  />
                </a-tooltip>
                </a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <s-table
        ref="table1"
        class="user_management_table"
        :rowKey="(record) => record.id"
        :columns="stuColumns"
        :data="loadStuData"
        :rowSelection="{ selectedRowKeys: stuselectedRowKeys, onChange: stuonSelectChange,getCheckboxProps:getCheckboxProps1 }"
        :scroll="{y:300}"
      ></s-table>
    </a-modal>

    <a-modal
      title="选择班级"
      v-model="visible2"
      @ok="handleOk2"
      :destroyOnClose="true"
      okText="选好了"
      width="800px"
    >
      <a-form>
        <a-row>
          <a-col :span="8">
            <a-form-item>
              <a-input v-model="className" placeholder="班级名称" style="width:80%"   @pressEnter="$refs.table2.refresh(true)">
                <a-tooltip slot="suffix" title="请输入班级名称">
                  <a-icon
                    type="search"
                    style="color: rgba(0,0,0,.45)"
                    @click="$refs.table2.refresh(true)"
                  />
                </a-tooltip>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item>
              <a-select v-model="queryParam2.course_id" placeholder="所属课程" style="width:80%"  allowClear>
                <a-select-option v-for="item in this.Iscourses" :key="item.id">{{item.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item>
              <a-select v-model="queryParam2.teacher_id" placeholder="授课老师" style="width:80%"  allowClear>
                <a-select-option v-for="item in this.Isteacher" :key="item.id">{{item.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <s-table
        ref="table2"
        :rowKey="(record) => record.id"
        :columns="classColumns"
        :data="loadClassData"
        :rowSelection="{ selectedRowKeys: classselectedRowKeys, onChange: classonSelectChange,getCheckboxProps:getCheckboxProps2 }"
        :scroll="{y:300}"
      >
        <span
          slot="student_num"
          slot-scope="text, record"
        >{{record.student_num}}/{{record.upper_limit||'未设置'}}</span>
      </s-table>
    </a-modal>
    <a-card
      :bordered="false"
      style="position: fixed;bottom: 0;left: 0;right: 0;padding: 0px 20px 0px 0px;margin: 0; background: #fff; display: flex;
    align-items: center;
    justify-content: flex-end;
    height:48px"
    >
      <a-button type="primary" @click="onSubmit(1)">发布</a-button>
      <a-button style="margin-left: 10px;" @click="onSubmit(2)">保存为草稿</a-button>
    </a-card>
  </div>
</template>

<script>
import moment from 'moment'
import { STable } from '@/components'
// import StepByStepModal from '../../list/modules/StepByStepModal'
// import CreateForm from '../../list/modules/CreateForm'
import { subjectsList, examsCreate } from '@/api/homeSchool'
import { classList } from '@/api/class'
import { studentList } from '@/api/student'
import { teacherList } from '@/api/teacher'
import { coursesList } from '@/api/courseCharge'
import topNavBar from '@/components/topNavBar/topNavBar'

export default {
  name: 'Single',
  components: {
    topNavBar,
    STable
  },
  data() {
    return {
      stuselectedRowKeys: [], //选择的  清空他用 this.selectedRowKeys = [];
      classselectedRowKeys: [], //选择的  清空他用 this.selectedRowKeys = [];
      selectedRowKeys1: [], //真正要用的，学员
      selectedRowKeys2: [], //真正要用的，班级
      stuColumns: [
        {
          title: '学员姓名',
          dataIndex: 'name',
          align: 'center'
        },
        {
          title: '手机号',
          dataIndex: 'main_phone',
          align: 'center'
        },
        {
          title: '年级',
          dataIndex: 'grade_name',
          align: 'center'
        }
      ],
      classColumns: [
        {
          title: '班级名称',
          dataIndex: 'name',
          align: 'center'
        },
        {
          title: '班级老师',
          dataIndex: 'teacher',
          align: 'center',
          customRender(teacher) {
            if (teacher.length > 0) {
              let teachers = teacher.map(function(item) {
                return item.name
              })
              return teachers.join('/')
            }
          }
        },
        {
          title: '人数/容量',
          dataIndex: 'student_num',
          align: 'center',
          scopedSlots: { customRender: 'student_num' }
        }
      ],
      visible1: false,
      visible2: false,
      studentName:undefined,
      queryParam1: {}, // 查询参数
      className:undefined,
      queryParam2: {}, // 查询参数

      visible: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 16 },
      form: {
        name: '',
        time: undefined,
        subject_id: undefined,
        school_id: undefined,
        is_show: '1',
        source_type: '1',
        type: '1', //1正式，2草稿
        is_statistics_show: '1',
        full_marks: undefined,
        score_arr: [
          // {
          //   student_id: 6,
          //   name: '学员姓名1',
          //   status: '2',
          //   comment: 'New York No. 1 Lake Park',
          //   score: '2'
          // },
          // {
          //   student_id: 4,
          //   name: 'John Brown',
          //   status: '1',
          //   comment: 'New York No. 1 Lake Park',
          //   score: '23'
          // },
          // {
          //   student_id: 11,
          //   name: 'John Brown',
          //   status: '1',
          //   comment: 'New York No. 1 Lake Park',
          //   score: '2' //默认为0
          // }
        ]
      },
      form_time: '', //日期
      nowRouteTitle: '',
      Isclass: [],
      Isstudent: [], //学员的数据，用选好的班级id和学生id做筛选
      Iscourses: [],
      Isteacher: [],
      Issubjects: [],
      rules: {
        subject_id: [{ required: true, message: '请选择', trigger: 'change' }],
        full_marks: [{ required: true, message: '请输入数字' }],
        time: [{ required: true, message: '请选择' }],
        source_type: [{ required: true, message: '请选择' }],
        name: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      },

      columns: [
        {
          title: '学员姓名',
          dataIndex: 'name',
          key: 'name',
          align: 'center'
        },
        {
          title: '分数',
          dataIndex: 'status',
          key: 'status',
          align: 'center',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '评语(选填)',
          dataIndex: 'comment',
          key: 'comment',
          align: 'center',
          scopedSlots: { customRender: 'comment' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      loadStuData: parameter => {
        return studentList(
          Object.assign(parameter, {school_id: this.$store.state.user.school,keywords: this.studentName }, this.queryParam1)
        ).then(res => {
          return res
        })
      },
      loadClassData: parameter => {
        return classList(Object.assign(parameter, this.queryParam2,{school_id: this.$store.state.user.school,keywords: this.className })).then(
          res => {
            return res
          }
        )
      },
      getCheckboxProps1: record => ({
        props: {
          disabled: this.selectedRowKeys1.some(item => item == record.id) // Column configuration not to be checked
        }
      }),
      getCheckboxProps2: record => ({
        // props: {
        //   disabled: this.selectedRowKeys2.some(item => item == record.id) // Column configuration not to be checked
        // }
      })
    }
  },
  watch: {
    queryParam2: {
      handler(val) {
        this.$refs.table2.refresh(true)
      },
      deep: true
    }
  },
  mounted() {
    this.school_id = this.$store.state.user.school //获取school_id
    this.$store.state.Isfather = false
    this.nowRouteTitle = this.$route.meta.title
    subjectsList({ pageSize: 999999, school_id: this.$store.state.user.school }).then(res => {
      // 获取科目信息
      this.Issubjects = res.data
    })
    teacherList({ pageSize: 999999,school_id: this.$store.state.user.school  }).then(res => {
      // 获取老师信息
      this.Isteacher = res.data
    })
    coursesList({ pageSize: 999999,school_id: this.$store.state.user.school }).then(res => {
      // 获取课程信息
      this.Iscourses = res.data
    })
    classList({ pageSize: 999999 }).then(res => {
      this.Isclass = res.data
    })
    studentList({ pageSize: 999999, school_id: this.$store.state.user.school }).then(res => {
      this.Isstudent = res.data
    })
  },
  destroyed() {
    this.$store.state.Isfather = true
  },

  methods: {
    create() {},
    handleSizeChange(data) {
      if (data.status == 2) {
        this.form.score_arr.forEach(function(item) {
          if (item.student_id == data.student_id) {
            item.score = 0
          }
        })
      }
    },
    table_del(e) {
      this.form.score_arr.splice(
        this.form.score_arr.findIndex(item => item.student_id === e.student_id),
        1
      )
      this.selectedRowKeys1.splice(
        this.selectedRowKeys1.findIndex(item => item === e.student_id),
        1
      )
    },

    back() {
      this.$router.go(-1)
    },
    onChange(date, dateString) {
      this.form_time = dateString //要
    },
    onSubmit(e) {
      this.form.type = e
      if(this.form.full_marks=='0'){
        this.$message.warning("满分不能为0分")
         return
      }
     
      if(this.form.score_arr.length==0){
        this.$message.warning("请先添加学生")
         return
      }
    
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          //验证通过
          let data = Object.assign({}, this.form)
          data.time = this.form_time //传值的时候转换
          data.school_id = this.$store.state.user.school
          data.score_arr = data.score_arr.map(function(item) {
            return { student_id: item.student_id, status: item.status, comment: item.comment, score: item.score }
          })
          examsCreate(data).then(res => {
            this.$message.success("成绩添加成功")
            this.$router.go(-1)
          }).catch(err=>{
              this.$message.error(err.data.message||"成绩添加成功")
          })
        } else {
          console.log('error submit!!验证失败')
          return false
        }
      })
    },
    showModal() {
      this.visible = true
    },
    handleOk(e) {
      this.visible = false
    },

    open1() {
      this.visible1 = true
    },
    open2() {
      this.visible2 = true
    },

    handleOk1() {
      //模态框确认1
      let selectedRowKeys = this.selectedRowKeys
      this.selectedRowKeys1 = this.stuselectedRowKeys
      let _this = this
      let score_arr = []
      let form_score_arr = this.form.score_arr
      this.Isstudent.map(function(item) {
        if (_this.selectedRowKeys1.some(listItem => listItem == item.id)) {
          score_arr.push({ student_id: item.id, name: item.name, status: '1', comment: '', score: 0 })
        }
      })
      form_score_arr = form_score_arr.concat(score_arr)

      let object = {}
      if (form_score_arr.length > 0) {
        this.form.score_arr = form_score_arr.reduce((item, next) => {
          object[next.student_id] ? '' : (object[next.student_id] = true && item.push(next))
          return item
        }, [])
      } else {
        this.form.score_arr = form_score_arr
      }

      this.visible1 = false
    },
    handleOk2() {
      //模态框确认2
      this.selectedRowKeys2 = this.classselectedRowKeys
      let _this = this
      let schoolId = this.$store.state.user.school
      this.selectedRowKeys2.map(function(item) {
        studentList({ pageSize: 999999, school_id: schoolId, class_id: item }).then(res => {
          // studentarr = studentarr.concat(res.data)
          if (res.data.length > 0) {
            res.data.map(function(data) {
              if (!_this.form.score_arr.some(arrItem => arrItem.student_id == data.id)) {
                _this.form.score_arr = _this.form.score_arr.concat({
                  student_id: data.id,
                  name: data.name,
                  status: '1',
                  comment: '',
                  score: 0
                })
              }
            })
          }
        })
      })
      this.visible2 = false
    },

    stuonSelectChange(selectedRowKeys) {
      this.stuselectedRowKeys = selectedRowKeys
    },
    classonSelectChange(selectedRowKeys) {
      this.classselectedRowKeys = selectedRowKeys
    }
  }
}
</script>
<style lang="less" scoped>
.nowPage {
  padding: 0 8px;
  border: none;
}
.a_row_bottom {
  border-bottom: 1px solid #c0c0c0;
  width: 100%;
  margin: 10px 0;
}
</style>